package javaMSCRM;
import java.awt.BorderLayout;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

import com.microsoft.schemas.crm._2006.query.AllColumns;
import com.microsoft.schemas.crm._2006.webservices.Customer;
import com.microsoft.schemas.crm._2006.webservices.Key;
import com.microsoft.schemas.crm._2006.webservices.Picklist;
import com.microsoft.schemas.crm._2007.webservices.Opportunity;
import com.microsoft.schemas.crm._2007.webservices.CreateDocument;
import com.microsoft.schemas.crm._2007.webservices.CreateResponseDocument;
import com.microsoft.schemas.crm._2007.webservices.DeleteDocument;
import com.microsoft.schemas.crm._2007.webservices.EntityName;
import com.microsoft.schemas.crm._2007.webservices.RetrieveDocument;
import com.microsoft.schemas.crm._2007.webservices.TargetUpdateOpportunity;
import com.microsoft.schemas.crm._2007.webservices.UpdateDocument;
import com.microsoft.schemas.crm._2007.webservices.UpdateResponseDocument;
import com.microsoft.schemas.crm._2007.webservices.CreateDocument.Create;
import com.microsoft.schemas.crm._2007.webservices.CreateResponseDocument.CreateResponse;
import com.microsoft.schemas.crm._2007.webservices.DeleteDocument.Delete;
import com.microsoft.schemas.crm._2007.webservices.RetrieveDocument.Retrieve;
import com.microsoft.schemas.crm._2007.webservices.UpdateDocument.Update;
import com.microsoft.schemas.crm._2007.webservices.TargetCreateOpportunity;

import net.miginfocom.layout.AC;
import net.miginfocom.layout.LC;
import net.miginfocom.swing.MigLayout;

/**
 * 
 */

/**
 * @author Zoran IVANOV
 *
 */
public class JavaMSCRMOpportunity extends Form {
	Opportunity record = null;
	JTextField 	JTFName=new JTextField(""),
				JTFCurrency=new JTextField("");
	LookupField LFPotentialCustomer;
	JComboBox JCBRating;
	String[] RatingItemsList = new String[]{
			"Hot",
			"Warm",
			"Cold"};
	JButton SaveButton,DeleteButton;
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * @param JavaMSCRM
	 */
	public JavaMSCRMOpportunity(JavaMSCRM JavaMSCRM) {
		super(JavaMSCRM);
		setTitle("New Opportunity");
		JScrollPane FormScrollPane = new JScrollPane(setupFields());
		FormScrollPane.setBorder(BorderFactory. createEmptyBorder(0,0,0,0));
		add(FormScrollPane, BorderLayout.CENTER);
		pack();
		setVisible(true);
	}
	
	/**
	 * @param JavaMSCRM
	 * @param Id
	 */
	public JavaMSCRMOpportunity(JavaMSCRM JavaMSCRM, String Id) {
		super(JavaMSCRM, Id);
		try {
	        RetrieveDocument rd = RetrieveDocument.Factory.newInstance();  
	        Retrieve r = Retrieve.Factory.newInstance();	        
	        r.setEntityName(EntityName.OPPORTUNITY.toString());
	        r.setId(Id);
	        r.setColumnSet(AllColumns.Factory.newInstance());	        
	        rd.setRetrieve(r);
	        record = (Opportunity) JavaMSCRM.stub.Retrieve(rd,  JavaMSCRM.catd, null, null).getRetrieveResponse().getRetrieveResult();
		}  
		catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.toString());
		}		
		setTitle("Opportunity: " + record.getName());
		JScrollPane FormScrollPane = new JScrollPane(setupFields());
		FormScrollPane.setBorder(BorderFactory. createEmptyBorder(0,0,0,0));
		add(FormScrollPane, BorderLayout.CENTER);
		pack();
		setVisible(true);
	}
	
	/**
	 * @return JPanel
	 */
	private JPanel setupFields(){
		LC layC = new LC().wrap();
		AC colC = new AC().align("right", 0).fill(1, 3).grow(100, 1, 3).align("right", 2).gap("15", 1);
		AC rowC = new AC().index(6).gap("15!").align("top").grow(100, 0);	
		JPanel form = new JPanel(new MigLayout(layC, colC, rowC));		
		JPanel formContainer = new JPanel(new MigLayout(layC, colC, rowC));		
		formContainer.add(form, BorderLayout.NORTH);			
		form.setBorder(BorderFactory. createEmptyBorder(0,0,0,0));
		//Create TextFields
		
		try{JTFName = new JTextField(record.getName());}catch (Exception e) {}
			
		LFPotentialCustomer = new LookupField(JavaMSCRM,EntityName.ACCOUNT.toString());
		try{LFPotentialCustomer.setValue(record.getCustomerid().getStringValue(), record.getCustomerid().getName());}catch (Exception e) {}		
		
		try{JTFCurrency = new JTextField(record.getTransactioncurrencyid().getName());}catch (Exception e) {}

		JCBRating = new JavaMSCRMComboBox(RatingItemsList, false);
		try{JCBRating.setSelectedItem(RatingItemsList[record.getOpportunityratingcode().getIntValue()-1]);}catch (Exception e) {}

		addSeparator(form, "General");		
		
		form.add(new JavaMSCRMLabel("Topic", true));		
		form.add(JTFName, "w 200:100:");
		form.add(new JavaMSCRMLabel("Potential Customer", true));
		form.add(LFPotentialCustomer, "w 200:100:");		
		form.add(new JavaMSCRMLabel("Currency", true));
		form.add(JTFCurrency, "w 200:100:");
		form.add(new JavaMSCRMLabel("Rating", false));
		form.add(JCBRating, "w 200:100:");
				
		return formContainer;
	}
	
	/* (non-Javadoc)
	 * @see JavaMSCRMForm#createRecord()
	 */
	public void createRecord(){
		String EntityId = "";
		try {
			TargetCreateOpportunity targetEntity = TargetCreateOpportunity.Factory.newInstance();
			Opportunity Entity = targetEntity.addNewOpportunity();
			
			Entity.setName(JTFName.getText());
			
			Customer C = Customer.Factory.newInstance();
			C.setName(LFPotentialCustomer.RecordName);
			C.setStringValue(LFPotentialCustomer.RecordId);
			C.setType("account");
			Entity.setCustomerid(C);
			
			//Entity.setTransactioncurrencyid(JTFCurrency.getText());
			Picklist ctc = Picklist.Factory.newInstance();
			ctc.setIntValue(JCBRating.getSelectedIndex()+1);
			Entity.setOpportunityratingcode(ctc);
						
			CreateDocument cd = CreateDocument.Factory.newInstance();
			Create create = Create.Factory.newInstance();
			create.setEntity(Entity);
			cd.setCreate(create);
		
			CreateResponseDocument crd = JavaMSCRM.stub.Create(cd, JavaMSCRM.catd, null, null);
			CreateResponse cr = crd.getCreateResponse();
			EntityId = cr.getCreateResult();
		}  
		catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.toString());
		}
		
		if(EntityId != ""){
			new Opportunities(JavaMSCRM);
			new JavaMSCRMOpportunity(JavaMSCRM,EntityId);
			dispose();
		}else{
			JOptionPane.showMessageDialog(null, "There was an error while creating the record!");
		}		
	}
	
	/* (non-Javadoc)
	 * @see JavaMSCRMForm#updateRecord()
	 */
	public void updateRecord(){
		try {
			TargetUpdateOpportunity targetEntity = TargetUpdateOpportunity.Factory.newInstance();
			Opportunity Entity = targetEntity.addNewOpportunity();

			Entity.setName(JTFName.getText());
			
			Customer C = Customer.Factory.newInstance();
			C.setName(LFPotentialCustomer.RecordName);
			C.setStringValue(LFPotentialCustomer.RecordId);
			C.setType("account");
			Entity.setCustomerid(C);
			
			//Entity.setTransactioncurrencyid(JTFCurrency.getText());
			Picklist ctc = Picklist.Factory.newInstance();
			ctc.setIntValue(JCBRating.getSelectedIndex()+1);
			Entity.setOpportunityratingcode(ctc);

			Key id = Key.Factory.newInstance();
			id.setStringValue(this.EntityId);
			Entity.setOpportunityid(id);
			
			UpdateDocument ud = UpdateDocument.Factory.newInstance();
			Update update = Update.Factory.newInstance();
			update.setEntity(Entity);
			ud.setUpdate(update);
			//JOptionPane.showMessageDialog(null, ud.toString());
			UpdateResponseDocument urd = this.JavaMSCRM.stub.Update(ud, JavaMSCRM.catd, null, null);
			urd.getUpdateResponse();
		}  
		catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.toString());
		}
		
		new Opportunities(JavaMSCRM);
		new JavaMSCRMOpportunity(this.JavaMSCRM,this.EntityId);
		dispose();
	}
	
	/* (non-Javadoc)
	 * @see JavaMSCRMForm#deleteRecord()
	 */
	public void deleteRecord(){
		String msg ="Record succesfuly deleted";
		int deleteConfirmation = JOptionPane.showConfirmDialog(null,
				"Are you sure you want to delete this record?",
	       		"Record Deletion Confirmation",  
		        JOptionPane.YES_NO_OPTION);
		if (deleteConfirmation == JOptionPane.YES_OPTION){
			try {
				DeleteDocument dd = DeleteDocument.Factory.newInstance();
				Delete d = Delete.Factory.newInstance();
				d.setId(this.EntityId);
				d.setEntityName(EntityName.OPPORTUNITY.toString());
				
				dd.setDelete(d);
				
				JavaMSCRM.stub.Delete(dd, JavaMSCRM.catd, null, null);
			}  
			catch (Exception e) {
				msg ="There was a problem while deleting some of the record!";
			}

			new Opportunities(JavaMSCRM);
			dispose();
			JOptionPane.showMessageDialog(null, msg);
		}
	}
}
